package com.qunar.wan.service;

import com.google.common.base.Preconditions;
import com.qunar.wan.common_api.model.Classify;
import com.qunar.wan.common_api.model.Query;
import com.qunar.wan.common_api.model.SubClassify;
import com.qunar.wan.common_api.service.CacheService;
import com.qunar.wan.common_api.service.ClassifyService;
import com.qunar.wan.common_api.service.SubClassifyService;
import com.qunar.wan.common_api.service.mapper.ClassifyMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * User: hangyu.shen Date: 13-11-27 Time: 下午7:41
 */
@Service("classifyService")
public class ClassifyServiceImpl extends BaseServiceImpl<Classify, ClassifyMapper> implements ClassifyService {

    @Resource
    private SubClassifyService subClassifyService;
    @Resource
    private CacheService cacheService;

    @Override
    public List<Classify> selectAll() {
        List<Classify> classifies = selectByQuery(new Query());
        return classifies;
    }

    @Override
    public List<Object> selectAllClassifyAndSub() {
        // 用于保存前端需要的Json数据
        List<Object> list = new ArrayList<Object>();
        // 获取所有大分类活动信息
        // List<Classify> classifies = selectAll();
        List<Classify> classifies = cacheService.readClasCache();
        Iterator<Classify> iter = classifies.iterator();
        while (iter.hasNext()) {
            // 用于存储大分类活动类别数据
            Map<String, Object> mapClassify = new HashMap<String, Object>();
            // 用于存储对应的子分类活动类别信息
            List<SubClassify> listSubClassify = new ArrayList<SubClassify>();
            // 获取一个大分类对应的所有子分类信息
            Classify classify = iter.next();
            // List<SubClassify> subClassifies = subClassifyService.selectListBySupId(classify.getId());
            List<SubClassify> subClassifies = cacheService.readSubsCache(classify.getId());
            for (SubClassify subClassify : subClassifies) {
                listSubClassify.add(subClassify);
            }
            mapClassify.put("id", classify.getId());
            mapClassify.put("name", classify.getClaName());
            mapClassify.put("child", listSubClassify);
            list.add(mapClassify);
        }
        return list;
    }

    @Override
    public Classify selectClassifyById(int id) {
        Preconditions.checkArgument(id > 0, "(ClassifyServiceImpl)id must greater than 0, your input is: " + id);
        List<Classify> classify = selectByQuery(new Query().fill("id", id));
        return classify.isEmpty() ? null : classify.get(0);
    }
}
